package aynu.oracle.video.util;

import org.bytedeco.javacv.*;
import org.bytedeco.javacpp.*;

import java.util.concurrent.Executors;

/*
*  将视频格式转换为mp4，需要设置输出的配置
* */
@Deprecated
public class ConvertVideoUtil {

    private boolean isStart = true;

    public void frameRecord(String inputFile, String outputFile)
            throws Exception, org.bytedeco.javacv.FrameRecorder.Exception {
        // 获取视频源
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        grabber.setOption("rtsp_transport", "tcp");
        //速度
        grabber.setFrameRate(15.08);
        //码率
        grabber.setVideoBitrate(29640000);
        // 流媒体输出地址，分辨率（长，高），是否录制音频（0:不录制/1:录制）
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 2160, 1080, 1);
        recorder.setFrameRate(15.08);
        recorder.setVideoBitrate(29640000);
        //编码格式
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
        recordByFrame(grabber, recorder);
    }

    private void recordByFrame(FFmpegFrameGrabber grabber, FFmpegFrameRecorder recorder)
            throws Exception {

        System.out.println(grabber+"____"+recorder);
        Executors.newCachedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                try {// 建议在线程中使用该方法

                    grabber.start();
                    recorder.start();

                    long t1 = System.currentTimeMillis();

                    Frame frame = null;


                    while (isStart && (frame = grabber.grabFrame()) != null) {
                        long t2 = System.currentTimeMillis();
                        if (t2 - t1 > 2 * 60 * 60 * 1000) {
                            break;
                        } else {
                            recorder.record(frame);
                        }
                    }

                    recorder.stop();
                    grabber.stop();

                } catch (FrameRecorder.Exception e) {
                    e.printStackTrace();
                } catch (FrameGrabber.Exception e) {
                    e.printStackTrace();
                } finally {
                    if (grabber != null) {
                        try {
                            grabber.stop();
                        } catch (FrameGrabber.Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

    }
}